//
//  YZMConfigureModel.m
//  YZMicroStock
//
//  Created by wangminhong on 16/4/13.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMConfigureModel.h"
#import "Mantle+Utils.h"
#import "JSONBaseDeal.h"
#import "YZMGridMoneyModel.h"
#import "YZMSeverTimeService.h"
#import "DTTimePeriod+Utils.h"
#import <DateTools/DateTools.h>
#import <LinqToObjectiveC/LinqToObjectiveC.h>

@implementation YZMConfigureModelForLever

+ (NSDictionary *)JSONKeyPathsByPropertyKey {
    return nil;
}

+ (instancetype)mapResponseDictionary:(NSDictionary *)dictionary{
    
    YZMConfigureModelForLever *instance = [YZMConfigureModelForLever new];
    instance.value = [JSONBaseDeal getDoubleValue:@"value" fromData:dictionary];
    instance.rate = [JSONBaseDeal getDoubleValue:@"value" fromData:dictionary[@"quitLossLineRatio"]];
    
    return instance;
}

@end

@interface YZMConfigureModel()

@property (nonatomic, strong) NSString *risk;
@property (nonatomic, strong) NSString *strategyRisk;
@property (nonatomic, strong) NSString *holidayString;

@end

@implementation YZMConfigureModel

+ (NSDictionary *)JSONKeyPathsByPropertyKey {
    return @{
             @"requestTime":@"nowTime",
//             @"isHoliday": @"isHoliday",
             @"unHanldDeferCharge":@"unHanldDeferCharge",
             @"balance":@"balance",
             @"buyCount":@"buyCount",
             @"gameTimeStatus":@"gameTimeStatus",
             @"token":@"token",
             @"userType":@"userType",
             @"risk":@"strRisk",
             @"strategyRisk":@"strategyRisk",
             @"signAgreement":@"signAgreement",
             @"holidayString":@"holidays"
             };
}

- (void)encodeWithCoder:(NSCoder *)coder{
    
    [coder encodeObject:self.limitTimePeriods forKey:@"limitTimePeriods"];
    [coder encodeObject:self.levers forKey:@"levers"];
    [coder encodeObject:self.defaultStockCode forKey:@"defaultStockCode"];
    [coder encodeInteger:self.maxStockCount forKey:@"maxStockCount"];
    [coder encodeInteger:self.userType forKey:@"userType"];
    [coder encodeObject:self.tradingMoneyList forKey:@"tradingMoneyList"];
    [coder encodeObject:self.priceRisk forKey:@"priceRisk"];
    [coder encodeObject:self.quitGainRatioList forKey:@"quitGainRatioList"];
    [coder encodeDouble:self.tradingCountRatio forKey:@"tradingCountRatio"];
    [coder encodeInteger:self.maxCountOneDay forKey:@"maxCountOneDay"];
    [coder encodeDouble:self.serviceCharge forKey:@"serviceCharge"];
    [coder encodeObject:self.version forKey:@"version"];
    [coder encodeDouble:self.maxMoneyOneStock forKey:@"maxMoneyOneStock"];
    [coder encodeDouble:self.deferCharge forKey:@"deferCharge"];
    [coder encodeDouble:self.deferChargeForLittleMoney forKey:@"deferChargeForLittleMoney"];
    [coder encodeDouble:self.serviceChargeForLittleMoney forKey:@"serviceChargeForLittleMoney"];
//    /* ylb */
//    [coder encodeDouble:self.totalSurplusMoney forKey:@"totalSurplusMoney"];
//    [coder encodeDouble:self.userSurplusMoney forKey:@"userSurplusMoney"];

    /*T+D*/
    [coder encodeDouble:self.quitLossRatio forKey:@"quitLossRatio"];
    [coder encodeDouble:self.profitShare forKey:@"profitShare"];
    [coder encodeDouble:self.deferConditionRatio forKey:@"deferConditionRatio"];
    [coder encodeDouble:self.quitGainRatio forKey:@"quitGainRatio"];
    [coder encodeObject:self.holdDayList forKey:@"holdDayList"];
    [coder encodeInteger:self.maxTradingDay forKey:@"maxTradingDay"];
    [coder encodeInteger:self.leverValue forKey:@"leverValue"];
}

- (instancetype)initWithCoder:(NSCoder *)coder{
    
    self = [super init];
    if (self) {
        
        self.limitTimePeriods = [coder decodeObjectForKey:@"limitTimePeriods"];
        self.levers = [coder decodeObjectForKey:@"levers"];
        self.defaultStockCode = [coder decodeObjectForKey:@"defaultStockCode"];
        self.maxStockCount = [coder decodeIntegerForKey:@"maxStockCount"];
        self.userType = [coder decodeIntegerForKey:@"userType"];
        self.tradingMoneyList = [coder decodeObjectForKey:@"tradingMoneyList"];
        self.priceRisk = [coder decodeObjectForKey:@"priceRisk"];
        self.quitGainRatioList = [coder decodeObjectForKey:@"quitGainRatioList"];
        self.tradingCountRatio = [coder decodeDoubleForKey:@"tradingCountRatio"];
        self.maxCountOneDay = [coder decodeIntegerForKey:@"maxCountOneDay"];
        self.serviceCharge = [coder decodeDoubleForKey:@"serviceCharge"];
        self.version = [coder decodeObjectForKey:@"version"];
        self.maxMoneyOneStock = [coder decodeDoubleForKey:@"maxMoneyOneStock"];
        self.deferCharge = [coder decodeDoubleForKey:@"deferCharge"];
        self.deferChargeForLittleMoney = [coder decodeDoubleForKey:@"deferChargeForLittleMoney"];
        self.serviceChargeForLittleMoney = [coder decodeDoubleForKey:@"serviceChargeForLittleMoney"];
//        /* ylb */
//        self.totalSurplusMoney = [coder decodeDoubleForKey:@"totalSurplusMoney"];
//        self.userSurplusMoney = [coder decodeDoubleForKey:@"userSurplusMoney"];
        
        /*T+D*/
        self.quitLossRatio = [coder decodeDoubleForKey:@"quitLossRatio"];
        self.profitShare = [coder decodeDoubleForKey:@"profitShare"];
        self.deferConditionRatio = [coder decodeDoubleForKey:@"deferConditionRatio"];
        self.quitGainRatio = [coder decodeDoubleForKey:@"quitGainRatio"];
        self.holdDayList = [coder decodeObjectForKey:@"holdDayList"];
        self.maxTradingDay = [coder decodeIntegerForKey:@"maxTradingDay"];
        self.leverValue = [coder decodeIntegerForKey:@"leverValue"];
    }
    
    return self;
}

- (BOOL)isInHolidayOrWeekendWithDate:(NSDate *)date{
    
    if ([self isInWeekendWithDate:date]) {
        
        return YES;
    }
    
    if ([self isInHolidayWithDate:date]) {
        
        return YES;
    }
    
    return NO;
}

- (BOOL)isInHolidayWithDate:(NSDate *)date{
    
    for (NSDate *holiday in self.holidayList) {
        if ([date isSameDay:holiday]) {
            
            return YES;
        }
    }
    
    return NO;
}

- (BOOL)isInWeekendWithDate:(NSDate *)date{
    
    return [date isWeekend];
}

- (BOOL)isInTradeTimePeriods{
    
    NSDate *severDate = [YZMSeverTimeService sharedService].severDate;
    
    if ([self isInHolidayOrWeekendWithDate:severDate]) {
        
        return NO;
    }
    
    if (self.limitTimePeriods.count == 0) {
        
        return YES;
    }
    
    for (DTTimePeriod *period in self.limitTimePeriods) {
        
        if ([period containsDate:[YZMSeverTimeService sharedService].severDate interval:DTTimePeriodIntervalOpen]) {
            
            return YES;
        }
    }
    
    return NO;
}

- (BOOL)isInTradeShowTimePeriods{
    
    NSDate *sDate = [YZMSeverTimeService sharedService].severDate;
    
    if ([self isInHolidayOrWeekendWithDate:sDate]) {
        
        return NO;
    }
    
    if (sDate.hour <9 || sDate.hour>15) {
        
        return NO;
    }
    
    if ( sDate.hour == 9 && sDate.minute < 30) {
        
        return NO;
    }
    
    if ( sDate.hour == 15 && sDate.minute > 30) {
        
        return NO;
    }

    return YES;
}

- (instancetype)initWithDictionary:(NSDictionary *)dictionaryValue error:(NSError **)error{
    
    self = [super initWithDictionary:dictionaryValue error:error];
    if (self == nil) return nil;
    
    /*节假日*/
    {
        if (self.holidayString.length != 0) {
            
            NSArray *temp = [self.holidayString componentsSeparatedByString:@","];
            if (temp.count != 0) {
                
                NSMutableArray *array  = [NSMutableArray array];
                for (NSString *day in temp) {
                    
                    NSDate *holiday = [NSDate dateWithString:day formatString:@"yyyy-MM-dd"];
                    if (holiday) {
                        
                        [array addObject:holiday];
                    }
                }
                
                if (array.count != 0) {
                    
                    self.holidayList = [NSArray arrayWithArray:array];
                }
            }
            self.holidayString = nil;
        }
    }
    
    NSString *jsonString;
    if (self.risk) {
        jsonString = self.risk;
    }else{
        jsonString=self.strategyRisk;
    }
    
    if (jsonString.length >0) {
        
        jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\r" withString:@""];
        jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\t" withString:@""];
        
        NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
        NSError *err;
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
        if (err) return nil;
        
        /*version*/
        {
            self.version = [JSONBaseDeal getValue:@"version" fromData:dict];
        }
        
        /*交易时间段*/
        {   
            NSString *string = dict[@"tradingTimeLimit"][@"value"];
            NSArray *periodArray = [string componentsSeparatedByString:@"|"];
            NSMutableArray *timePeriodArray = [NSMutableArray array];
            for (NSString *subString in periodArray) {
                
                NSArray *periodSubArray = [subString componentsSeparatedByString:@","];
                if (periodArray.count < 2) continue;
                
                NSDate *useDate = [YZMSeverTimeService sharedService].severDate;
                NSArray *firstSeparate = [periodSubArray[0] componentsSeparatedByString:@":"];
                NSString *hour = firstSeparate[0];
                NSString *minute = firstSeparate[1];
                
                NSArray *secondSeparate = [periodSubArray[1] componentsSeparatedByString:@":"];
                NSString *endHour = secondSeparate[0];
                NSString *endMinute = secondSeparate[1];

                NSInteger year = [[useDate formattedDateWithFormat:@"yyyy"] integerValue];
                NSInteger month = [[useDate formattedDateWithFormat:@"MM"] integerValue];
                NSInteger day = [[useDate formattedDateWithFormat:@"dd"] integerValue];
                NSDate *beginDate = [NSDate dateWithYear:year month:month day:day hour:[hour integerValue] minute:[minute integerValue]second:0];
                NSDate *endDate = [NSDate dateWithYear:year month:month day:day hour:[endHour integerValue] minute:[endMinute integerValue]second:0];
                
                DTTimePeriod *timePeriod = [DTTimePeriod timePeriodWithStartDate:beginDate endDate:endDate];
                if (timePeriod) {
                    
                    [timePeriodArray addObject:timePeriod];
                }
            }
            if (timePeriodArray.count > 0) {
                
                self.limitTimePeriods = timePeriodArray;
            }
        }
        
        /*止损数组*/
        {
            NSArray *leverArray = dict[@"levers"][@"levers"];
            NSMutableArray *savedArray = [NSMutableArray array];
            for (NSDictionary *dic in leverArray) {
                
                YZMConfigureModelForLever *instance = [YZMConfigureModelForLever mapResponseDictionary:dic];
                if (instance) {
                    [savedArray addObject:instance];
                }
            }
            
            if (savedArray.count > 0) {
                self.levers = savedArray;
            }
        }
        
        /*默认股票代码*/
        {
            self.defaultStockCode = [JSONBaseDeal getValue:@"value" fromData:dict[@"defaultStock"]];
        }
        
        /*单次单股最大交易数量*/
        {
            self.maxStockCount = [JSONBaseDeal getIntValue:@"value" fromData:dict[@"maxStockCount"]];
        }
        
        {
            self.totalMoney = [JSONBaseDeal getDoubleValue:@"value" fromData:dict[@"totalMoney"]];
        }
        
        /*可选金额列表*/
        {
            NSString *string = [JSONBaseDeal getValue:@"value" fromData:dict[@"tradingMoneyList"]];
            if (string.length > 0) {
                
                NSArray *array = [string componentsSeparatedByString:@","];
                if (array.count >0) {
                    
                    self.tradingMoneyList = [array linq_select:^id(NSString *item) {
                        
                        YZMGridMoneyModel *model = [YZMGridMoneyModel new];
                        model.money = item.doubleValue;
                        return model;
                    }];
                }
            }
        }
        
        /*股价振幅超出此范围的禁止买入*/
        {
            NSString *string = [JSONBaseDeal getValue:@"value" fromData:dict[@"priceRisk"]];
            if (string.length > 0) {
                
                NSArray *array = [string componentsSeparatedByString:@","];
                if (array.count == 2) {
                    
                    self.priceRisk = [array linq_select:^id(NSString *item) {
                        return @(item.doubleValue);
                    }];
                }
            }
        }
        
        /*止盈线数组*/
        {
            NSString *string = [JSONBaseDeal getValue:@"value" fromData:dict[@"quitGainRatioList"]];
            if (string.length > 0) {
                
                NSArray *array = [string componentsSeparatedByString:@","];
                if (array.count > 0) {
                    
                    self.quitGainRatioList = [array linq_select:^id(NSString *item) {
                        return @(item.doubleValue);
                    }];
                }
            }
            
        }
        
        /*可交易股票除以的参数*/
        {
            self.tradingCountRatio = [JSONBaseDeal getDoubleValue:@"value" fromData:dict[@"tradingCountRatio"]];
        }
        
        /*一天最大购买次数*/
        {
            self.maxCountOneDay = [JSONBaseDeal getIntValue:@"value" fromData:dict[@"maxCountOneDay"]];
        }
        
        /*T+1：每1万元的交易综合费  
          T+D：每次交易金额的万分之，交易金额不足一万按一万算*/
        {
            self.serviceCharge = [JSONBaseDeal getDoubleValue:@"value" fromData:dict[@"serviceCharge"]];
        }
        
        /*递延规则*/
        {
            self.deferThreshHoldRatio = [JSONBaseDeal getDoubleValue:@"value" fromData:dict[@"deferThreshHoldRatio"]];
        }
        
        /*个股持仓累计金额的最大值*/
        {
            self.maxMoneyOneStock = [JSONBaseDeal getDoubleValue:@"value" fromData:dict[@"maxMoneyOneStock"]];
        }
        
        /*T+1：每1万元递延一天的费用
          T+D：方案金额的万分之*/
        {
            self.deferCharge = [JSONBaseDeal getDoubleValue:@"value" fromData:dict[@"deferCharge"]];
        }
        
        /*T+D：止损比例*/
        {
            self.quitLossRatio = [JSONBaseDeal getDoubleValue:@"value" fromData:dict[@"quitLossRatio"]];
        }
        
        /*T+D：盈利分成*/
        {
            self.profitShare = [JSONBaseDeal getDoubleValue:@"value" fromData:dict[@"profitShare"]];
        }
        
        /*T+D：递延条件比例*/
        {
            self.deferConditionRatio = [JSONBaseDeal getDoubleValue:@"value" fromData:dict[@"deferConditionRatio"]];
        }
        
        /*T+D：止盈比例*/
        {
            self.quitGainRatio = [JSONBaseDeal getDoubleValue:@"value" fromData:dict[@"quitGainRatio"]];
        }
        
        /*T+D：持仓时间组*/
        {
            NSString *string = [JSONBaseDeal getValue:@"value" fromData:dict[@"holdDayList"]];
            if (string.length > 0) {
                
                NSArray *array = [string componentsSeparatedByString:@","];
                if (array.count > 0) {
                    
                    self.holdDayList = [array linq_select:^id(NSString *item) {
                        return @(item.doubleValue);
                    }];
                }
            }
        }

        /*T+D：最大交易日*/
        {
            self.maxTradingDay = [JSONBaseDeal getIntValue:@"value" fromData:dict[@"maxTradingDay"]];
        }
        
        /*T+D：杠杆倍数*/
        {
            self.leverValue = [JSONBaseDeal getIntValue:@"value" fromData:dict[@"leverValue"]];
        }
        
        /*万元以下递延费*/
        {
            self.deferChargeForLittleMoney = [[JSONBaseDeal getValue:@"value" fromData:dict[@"deferChargeForLittleMoney"]] doubleValue];;
        }
        
        /*万元以下交易综合费*/
        {
            self.serviceChargeForLittleMoney = [[JSONBaseDeal getValue:@"value" fromData:dict[@"serviceChargeForLittleMoney"]]doubleValue];
        }
    }
    
    self.risk = nil;
    
    return self;
}

+ (NSValueTransformer *)requestTimeJSONTransformer
{
    return [NSValueTransformer valueTransformerForName: MTLDoubleDateTransformerName];
}

+ (NSValueTransformer *)unHanldDeferChargeJSONTransformer
{
    return [NSValueTransformer valueTransformerForName: MTLStringDoubleTransformerName];
}

+ (NSValueTransformer *)balanceJSONTransformer
{
    return [NSValueTransformer valueTransformerForName: MTLStringDoubleTransformerName];
}

- (void)setNilValueForKey:(NSString *)key{
    
}

#define sYZMConfigureDataDefault  @"YZMConfigureDataDefault"

- (void)createEncoderWithIdentify:(NSString *)identify {
    
    NSMutableData *data = [NSMutableData data];
    //创建一个归档类
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
    [archiver encodeObject:self forKey:identify];
    [archiver finishEncoding];
    //将数据写入文件里
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:identify];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (instancetype)createDecoderWithIdentify:(NSString *)identify {
    
    NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:identify];
    
    if (data && data.length != 0) {
        
        NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
        
        YZMConfigureModel *model = [unarchiver decodeObjectForKey:identify];
        [unarchiver finishDecoding];
        
        return model;
    }
    
    return nil;
}

- (void)createEncoder {
    
    [self createEncoderWithIdentify:sYZMConfigureDataDefault];
}

+ (instancetype)createDecoder {
    
    return [self createDecoderWithIdentify:sYZMConfigureDataDefault];
}

- (instancetype)copyWithZone:(NSZone *)zone{
    
    YZMConfigureModel *copy = [[[self class] allocWithZone:zone] init];
    copy.requestTime = [self.requestTime copyWithZone:zone];
//    copy.isHoliday = self.isHoliday;
    copy.holidayList = [self.holidayList copyWithZone:zone];
    copy.unHanldDeferCharge = self.unHanldDeferCharge;
    
    copy.balance = self.balance;
    copy.buyCount = self.buyCount;
    copy.gameTimeStatus=self.gameTimeStatus;
    copy.token = [self.token copyWithZone:zone];
    copy.userType=self.userType;
    copy.deferCharge = self.deferCharge;
    copy.limitTimePeriods = [self.limitTimePeriods copyWithZone:zone];
    copy.levers = [self.levers copyWithZone:zone];
    copy.defaultStockCode = [self.defaultStockCode copyWithZone:zone];
    copy.maxStockCount = self.maxStockCount;
    copy.tradingMoneyList = [self.tradingMoneyList copyWithZone:zone];
    copy.priceRisk = [self.priceRisk copyWithZone:zone];
    copy.quitGainRatioList = [self.quitGainRatioList copyWithZone:zone];
    copy.tradingCountRatio = self.tradingCountRatio;
    copy.maxCountOneDay = self.maxCountOneDay;
    copy.serviceCharge = self.serviceCharge;
    copy.version = [self.version copyWithZone:zone];
    copy.maxMoneyOneStock = self.maxMoneyOneStock;
    copy.signAgreement = self.signAgreement;
    /*T+D*/
    copy.quitLossRatio = self.quitLossRatio;
    copy.profitShare = self.profitShare;
    copy.deferConditionRatio = self.deferConditionRatio;
    copy.quitGainRatio = self.quitGainRatio;
    copy.holdDayList = [self.holdDayList copyWithZone:zone];
    copy.maxTradingDay = self.maxTradingDay;
    copy.leverValue = self.leverValue;
    copy.deferChargeForLittleMoney = self.deferChargeForLittleMoney;
    copy.serviceChargeForLittleMoney = self.serviceChargeForLittleMoney;
    return copy;
}

@end

@implementation YZMTDConfigureModel

#define sYZMTDConfigureDataDefault  @"YZMTDConfigureDataDefault"

- (void)createEncoder {
    
    [self createEncoderWithIdentify:sYZMTDConfigureDataDefault];
}

+ (instancetype)createDecoder {
    
    return [self createDecoderWithIdentify:sYZMTDConfigureDataDefault];
}

@end

@implementation YZMYLBConfigureModel

+ (NSDictionary *)JSONKeyPathsByPropertyKey {
    return @{
             @"requestTime":@"nowTime",
             @"unHanldDeferCharge":@"unHanldDeferCharge",
             @"balance":@"balance",
             @"buyCount":@"buyCount",
             @"gameTimeStatus":@"gameTimeStatus",
             @"token":@"token",
             @"userType":@"userType",
             @"risk":@"strRisk",
             @"strategyRisk":@"strategyRisk",
             @"signAgreement":@"signAgreement",
             @"holidayString":@"holidays",
             @"totalSurplusMoney":@"totalSurplusMoney",
             @"userSurplusMoney":@"userSurplusMoney"
             };
}

- (void)encodeWithCoder:(NSCoder *)coder{
    [super encodeWithCoder:coder];
    [coder encodeDouble:self.totalSurplusMoney forKey:@"totalSurplusMoney"];
    [coder encodeDouble:self.userSurplusMoney forKey:@"userSurplusMoney"];
}

- (id)initWithCoder:(NSCoder *)coder{
    self = [super initWithCoder:coder];
    if (self) {
        self.totalSurplusMoney = [coder decodeDoubleForKey:@"totalSurplusMoney"];
        self.userSurplusMoney = [coder decodeDoubleForKey:@"userSurplusMoney"];
    }
    return self;
}


#define sYZMYLBConfigureDataDefault  @"YZMYLBConfigureDataDefault"

- (void)createEncoder {
    
    [self createEncoderWithIdentify:sYZMYLBConfigureDataDefault];
}

+ (instancetype)createDecoder {
    
    return [self createDecoderWithIdentify:sYZMYLBConfigureDataDefault];
}

@end

@implementation YZMONEConfigureModel

#define sYZMONEConfigureDataDefault  @"YZMONEConfigureDataDefault"

- (void)createEncoder {
    
    [self createEncoderWithIdentify:sYZMONEConfigureDataDefault];
}

+ (instancetype)createDecoder {
    
    return [self createDecoderWithIdentify:sYZMONEConfigureDataDefault];
}

@end

@implementation YZMSIMUConfigureModel

#define sYZMSIMConfigureDataDefault  @"YZMSIMConfigureDataDefault"

- (void)createEncoder {
    
    [self createEncoderWithIdentify:sYZMSIMConfigureDataDefault];
}

+ (instancetype)createDecoder {
    
    return [self createDecoderWithIdentify:sYZMSIMConfigureDataDefault];
}


@end

@implementation YZMFreeExperienceConfigureModel

#define sYZMFreeExperienceConfigureDataDefault  @"YZMFreeExperienceConfigureDataDefault"

- (void)createEncoder {
    
    [self createEncoderWithIdentify:sYZMFreeExperienceConfigureDataDefault];
}

+ (instancetype)createDecoder {
    
    return [self createDecoderWithIdentify:sYZMFreeExperienceConfigureDataDefault];
}


@end


